package com.itcoon.cloud.framework.security.utils;/**
 * @author Athric Yu
 * 2025/1/6
 **/

import com.itcoon.cloud.framework.ex.Assertion;
import com.itcoon.cloud.framework.security.ex.SecurityResponseEnum;
import com.itcoon.cloud.framework.security.model.AuthToken;
import com.itcoon.cloud.framework.utils.SpringUtils;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;

import java.time.LocalDateTime;

/**
 *
 *
 * @author Athric Yu
 * 2025/1/6
 **/
public class AuthTokenUtil {

    private static final RedissonClient CLIENT = SpringUtils.getBean(RedissonClient.class);
    private static final String AUTHORIZATION_BUCKET = "AUTHORIZATION_BUCKET";

    public static AuthToken getToken(Long userId){
        RMap<Object, Object> map = CLIENT.getMap(AUTHORIZATION_BUCKET);
        return (AuthToken) map.get(userId);
    }

    public static void saveToken(Long userId, AuthToken token){
        RMap<Object, Object> map = CLIENT.getMap(AUTHORIZATION_BUCKET);
        map.put(userId, token);
    }

    public static void verifyToken(AuthToken authToken) {
        Assertion.assertNotNull(authToken).raise(SecurityResponseEnum.BAD_TOKEN);
        Assertion.assertTrue(!authToken.getLocked()).raise(SecurityResponseEnum.TOKEN_LOCKED);
    }

    public static boolean isTokenExpired(AuthToken authToken) {
        return authToken.getAccessExpiration().isBefore(LocalDateTime.now());
    }

    public static void removeTokenByKey(Long userId) {
        RMap<Object, Object> map = CLIENT.getMap(AUTHORIZATION_BUCKET);
        map.remove(userId);
    }


}
